import React, { useState, useRef, useEffect } from 'react'
import { Check, X } from 'lucide-react'
import { Badge } from '@/components/ui/badge'

interface Option {
  value: string
  label: string
}

interface MultiSelectProps {
  placeholder?: string
  options: Option[]
  value: string[]
  onChange: (value: string[]) => void
  onClose?: (hasChanged: boolean) => void // 修改为返回是否有变化
  onOutsideClick?: (hasChanged: boolean) => void // 同样返回是否有变化
  className?: string
  disabled?: boolean
  maxHeight?: number
}

export const MultiSelect: React.FC<MultiSelectProps> = ({
  placeholder = 'Select options',
  options = [],
  value = [],
  onChange,
  onClose,
  onOutsideClick,
  className = '',
  disabled = false,
  maxHeight = 300,
}) => {
  const [isOpen, setIsOpen] = useState<boolean>(false)
  const containerRef = useRef<HTMLDivElement>(null)
  const dropdownRef = useRef<HTMLDivElement>(null)
  const initialValueRef = useRef<string[]>([])

  // 当打开下拉框时，存储初始值
  useEffect(() => {
    if (isOpen) {
      initialValueRef.current = [...value]
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpen])

  // 检查值是否发生变化
  const hasValuesChanged = (currentValue: string[] = value) => {
    if (initialValueRef.current.length !== currentValue.length) return true
    return !initialValueRef.current.every((v) => currentValue.includes(v))
  }

  // 处理点击外部关闭
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        containerRef.current &&
        !containerRef.current.contains(event.target as Node)
      ) {
        const changed = hasValuesChanged()
        setIsOpen(false)
        onOutsideClick?.(changed) // 触发点击外部回调
      }
    }

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside)
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpen, onOutsideClick, value])

  // 调整下拉框位置，防止溢出屏幕
  useEffect(() => {
    if (isOpen && dropdownRef.current && containerRef.current) {
      const dropdownRect = dropdownRef.current.getBoundingClientRect()
      const containerRect = containerRef.current.getBoundingClientRect()
      const viewportHeight = window.innerHeight

      if (containerRect.bottom + dropdownRect.height > viewportHeight) {
        dropdownRef.current.style.bottom = `${containerRect.height}px`
        dropdownRef.current.style.top = 'auto'
      } else {
        dropdownRef.current.style.top = `${containerRect.height + 4}px`
        dropdownRef.current.style.bottom = 'auto'
      }
    }
  }, [isOpen])

  const handleSelect = (clickedValue: string) => {
    if (disabled) return

    let newValue: string[]
    if (value.includes(clickedValue)) {
      newValue = value.filter((v) => v !== clickedValue)
    } else {
      newValue = [...value, clickedValue]
    }
    onChange(newValue)
  }

  const removeValue = (valueToRemove: string, e: React.MouseEvent) => {
    if (disabled) return

    e.stopPropagation()
    const newValue = value.filter((v) => v !== valueToRemove)
    onChange(newValue)
    if (!isOpen) {
      onOutsideClick?.(true)
    }
  }

  // 处理关闭逻辑
  const handleClose = () => {
    const changed = hasValuesChanged()
    setIsOpen(false)
    onClose?.(changed)
  }

  const clearAll = (e: React.MouseEvent) => {
    if (disabled) return

    e.stopPropagation()
    onChange([])
    handleClose()
    const changed = hasValuesChanged([])
    onOutsideClick?.(changed)
  }

  return (
    <div ref={containerRef} className={`relative w-full ${className}`}>
      <div
        className={`
          relative w-full border rounded-md p-2 min-h-10 flex flex-wrap gap-1
          ${disabled ? 'bg-gray-100 cursor-not-allowed' : 'cursor-pointer'}
          ${isOpen ? 'border-black ring-2 ring-blue-100' : ''}
        `}
        onClick={() => !disabled && setIsOpen(!isOpen)}
      >
        {value.length > 0 ? (
          <>
            {value.map((v) => (
              <Badge key={v} variant="secondary" className="mr-1 mb-1">
                {options.find((opt) => opt.value === v)?.label || v}
                <button
                  className="ml-1 hover:bg-gray-200 rounded-full"
                  onClick={(e) => {
                    e.stopPropagation()
                    removeValue(v, e)
                  }}
                  disabled={disabled}
                >
                  <X className="h-3 w-3" />
                </button>
              </Badge>
            ))}
          </>
        ) : (
          <span className="text-gray-500">{placeholder}</span>
        )}
      </div>

      {isOpen && !disabled && (
        <div
          ref={dropdownRef}
          className="absolute z-50 w-full bg-white border rounded-md shadow-lg"
          style={{ maxHeight }}
        >
          <div
            className="my-scrollbar overflow-y-auto scrollbar-thin scrollbar-thumb-gray-300 scrollbar-track-gray-100 hover:scrollbar-thumb-gray-400"
            style={{ maxHeight: `${maxHeight - 16}px` }}
          >
            {value.length > 0 && (
              <div className="sticky top-0 p-2 bg-white border-b px-3">
                <button
                  className="text-sm text-gray-500 hover:text-gray-700"
                  onClick={clearAll}
                >
                  Clear all
                </button>
              </div>
            )}
            {options.map((option) => (
              <div
                key={option.value}
                className={`
                  flex items-center justify-between p-2 cursor-pointer px-3
                  ${value.includes(option.value) ? 'bg-gray-100' : 'hover:bg-gray-50'}
                `}
                onClick={() => handleSelect(option.value)}
              >
                <span>{option.label}</span>
                {value.includes(option.value) && <Check className="h-4 w-4" />}
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}

// 使用示例
// const MultiSelectExample: React.FC = () => {
//   const [selectedValues, setSelectedValues] = useState<string[]>([])

//   const options: Option[] = [
//     { value: 'tag1', label: '海外白人博主' },
//     { value: 'tag2', label: '海外黑人博主' },
//     { value: 'tag3', label: '海外亚洲人博主' },
//     { value: 'tag4', label: '女性' },
//     { value: 'tag5', label: '横屏' },
//     { value: 'tag6', label: '竖屏' },
//     { value: 'tag7', label: '测试公共资源' },
//   ]

//   const handleOutsideClick = (hasChanged: boolean) => {
//     console.log('点击了外部区域，值是否变化：', hasChanged)
//     // 这里可以处理你的业务逻辑
//   }

//   const handleClose = (hasChanged: boolean) => {
//     console.log('下拉框关闭，值是否变化：', hasChanged)
//     // 这里可以处理你的业务逻辑
//   }

//   return (
//     <div className="w-full max-w-md p-4">
//       <MultiSelect
//         options={options}
//         value={selectedValues}
//         onChange={setSelectedValues}
//         placeholder="选择标签"
//         onOutsideClick={handleOutsideClick}
//         onClose={handleClose}
//         maxHeight={300}
//       />
//     </div>
//   )
// }

// export default MultiSelectExample
